<?php

namespace App\Console\Commands;

use App\Facades\ChargeRecordService;
use App\Facades\DeviceService;
use App\Models\ChargeRecord;
use Cache;
use Illuminate\Console\Command;

class OfflineRecharge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'offline-recharge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Device offline recharge';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $chargeRecords = ChargeRecordService::getChargeListByStatus(ChargeRecord::ORDER_STATUS_OFFLINE_RECHARGE);
        foreach($chargeRecords as $chargeRecord){
            $deviceCode = $chargeRecord->device->code;
            if(!DeviceService::isOffline($deviceCode, false)){
                $originalTime = Cache::get($deviceCode.'state')['timeLimit'];
                $originalRlow = Cache::get($deviceCode.'state')['residualFlow'];
                switch(substr($deviceCode, 0, 2)){
                    case '21':
                        switch ($chargeRecord->recharge_mode) {
                            case 1:
                                $chargeRecord->update([
                                    "residual_flow" => $originalRlow,
                                    ]);
                                DeviceService::control('mode_recharge', $chargeRecord->days*24*60*60, $deviceCode, $chargeRecord->id, null, false, $chargeRecord->recharge_mode);
                                break;
                            case 2:
                                $chargeRecord->update([
                                    "time_limit" => $originalTime,
                                    ]);
                                DeviceService::control('mode_recharge', $chargeRecord->flow, $deviceCode, $chargeRecord->id, null, false);
                                break;
                            default:
                                # code...
                                break;
                        }
                        break;
                case '20':
                    if($chargeRecord->recharge_mode == 2){
                        $chargeRecord->update([
                            "residual_flow" => $originalRlow + $chargeRecord->flow,
                            ]);
                        DeviceService::control('recharge', $chargeRecord->flow, $deviceCode, $chargeRecord->id, null, false);
                    }
                    break;
                }
            }
        }
    }
}
